/*
 * @Author: cai.qi 
 * @Date: 2020-01-07 16:27:10 
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-05-13 19:16:09
 */


"use strict";
import { Controller } from "egg";
import wxConfig from '../../config/wx'
class TypeController extends Controller {
    docTransfer: {
        errotType: { type: string; required: boolean };
        errorInfo: { type: string; required: boolean };
        fromUrl: { type: string; required: boolean };
    };
    constructor(ctx) {
        super(ctx);
        this.docTransfer = {
            errotType: { type: "string", required: true },
            fromUrl: { type: "string", required: true },
            errorInfo: { type: "object", required: true }
        };
    }
    // ========================================  wx-login
    async configs() {
        const { ctx } = this;
        const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wxConfig.appId}&secret=${wxConfig.appSecret}&code=${ctx.query.code}&grant_type=authorization_code`
        const { res } = await this.ctx.curl(url, {
            method: "GET",
            dataType: "json",
        });

        if (res.data.errcode) {
            return ctx.throw('code timeout', 201);
        }
        const userinfo_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${res.data.access_token}&openid=${res.data.openid}&lang=zh_CN`

        const userInfo = await this.ctx.curl(userinfo_url, {
            method: "GET",
            dataType: "json",
        });
        const body = {
            openid: userInfo.data.openid,
            nickname: userInfo.data.nickname,
            sex: userInfo.data.sex === 1 ? '男' : '女',
            city: userInfo.data.city,
            province: userInfo.data.province,
            country: userInfo.data.country,
            headimgurl: userInfo.data.headimgurl,
        }

        const { data } = await ctx.service.sevUser.create(body);
        console.log('data', data)
        ctx.helper.success({ data });
    }

    // ========================================  js-sdk-config
    async sdk_config() {
        const { ctx } = this;
        const data = await ctx.service.sevWx.get_sdk_config();
        ctx.helper.success({ data });
    }
}

export default TypeController;
